<?php
class UserHelper
{
	public static function add($data)
	{
		$user_id = 0;
		try
		{
			$data['addtime'] = time();
			$user_id	= User::add($data);
		}
		catch(Exception $_){
			return false;
		}
		return $user_id;
	}

	public static function modify($user_id, $data)
	{
		unset($data['account']);

		if(!$data['passwd']){ unset($data['passwd']); }
		else{ $data['passwd'] = UserAuthHelper::encrypt($data['passwd']); }

		return User::update($user_id, $data);
	}

	public function getListWithPrivs(){
		$list = User::getList();
		foreach($list as &$u){
			$u['privs'] = RoleHelper::getByUser($u['id']);
			unset($u);
		}
		return $list;
	}

	/**
	 * 分配用户(非虚拟)角色。同一用户可分配多个角色
	 *
	 * @param $role_id	int|array	指定增加的角色ID(或数组)
	 */
	public static function assumeRole($user_id, $role_id)
	{
		if(!intval($user_id)) {
			return false;
		}

		if(!is_array($role_id)) {
			$role_id	=	array($role_id);
		}
		$role_id = array_map('intval', $role_id);
		foreach($role_id as $rid)
		{
			if($rid){
				Db::get('UserRole')->insert(array('user_id'=>$user_id,'role_id'=>$rid))->exec();
			}
		}
		
		return true;
	}

	/**
	 * 取用户role列表，用于显示
	 */
	public static function getRoles($user_id)
	{
		return Db::get('_user_role')->select('role_name')->where(array('user_id'=>$user_id))->order('role_sort ASC,role_id DESC')->hkey('role_id')->getCols();
	}

	/**
	 * 清空授与某人的所有角色/不含虚拟角色
	 */
	public static function purgeRoles($user_id)
	{
		return Db::get('UserRole')->delete()->where(array('user_id'=>$user_id))->exec();
	}
	
	public static function getNamesByIds($ids=array()){
		$tmp  = Db::get('User')->select('name')->where(array('id','in',$ids))->hkey('id')->getCols();
		$list = array();
		foreach($ids as $id){ $list[$id] = $tmp[$id]; }
		return $list;
	}
	
}
?>
